package com.mynews.activities.login;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Application;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.mynews.activities.App;
import com.mynews.activities.main.MainActivity;
import com.mynews.activities.sign.SignActivity;
import com.mynews.bean.User;
import com.mynews.utils.BmobApi;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class LoginVM extends AndroidViewModel {
    public static MutableLiveData<String> account=new MutableLiveData<>(),password=new MutableLiveData<>();
    public static MutableLiveData<Boolean> autoLogin=new MutableLiveData<>();
    @SuppressLint("StaticFieldLeak")
    private static LoginActivity loginActivity;
    public LoginVM(@NonNull Application application) {
        super(application);
        account.setValue("");
        password.setValue("");
        autoLogin.setValue(false);
        //判断自动登录
        if (App.sp.getBoolean("autoLogin",false)){
            String acc = App.sp.getString("account", "");
            String pass=App.sp.getString("password","");
            loginByLC(acc,pass,true);
        }
    }
    public static void sign(View view){
        loginActivity.startActivityForResult(new Intent(loginActivity, SignActivity.class),1);
    }
    public static void login(View view)  {
        loginByLC(account.getValue(),password.getValue(),autoLogin.getValue());
    }
    public static void loginByLC(String acc,String pass,boolean isAutoLogin){

        SharedPreferences.Editor edit = App.sp.edit();
        edit.putBoolean("autoLogin",isAutoLogin);
        edit.putString("account",acc);
        edit.putString("password",pass);
        edit.apply();
        BmobApi.get("https://api2.bmob.cn/1/login?username=" + acc + "&password=" + pass, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) { loginActivity.runOnUiThread(() -> Toast.makeText(loginActivity,"注册失败"+e.getMessage(),Toast.LENGTH_SHORT).show()); }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) {
                try {
                    JSONObject res=new JSONObject(response.body().string());
                    if (res.isNull("error")){
                        loginActivity.runOnUiThread(() -> {
                            try {
                                App.user=new User(res.getString("email"), res.getString("sessionToken"), res.getString("objectId"), res.getString("username"), res.getString("nickname"), res.getBoolean("isAdmin"));
                                loginActivity.startActivity(new Intent(loginActivity, MainActivity.class));
                                loginActivity.finish();
                            } catch (JSONException e){
                                e.printStackTrace();
                            }
                        });
                    }else {
                        loginActivity.runOnUiThread(() -> {
                            try {Toast.makeText(loginActivity,"登录失败"+res.getString("error"),Toast.LENGTH_SHORT).show();} catch (JSONException e){e.printStackTrace();}
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    public static void findPassword(View view){
        EditText editText=new EditText(loginActivity);
        editText.setHint("请输入您注册时的邮箱");
        AlertDialog.Builder dialog=new AlertDialog.Builder(loginActivity);
        dialog.setTitle("找回密码").setView(editText).setPositiveButton("确定", (dialog1, which) -> {
            try {
                JSONObject json=new JSONObject();
                json.put("email",editText.getText().toString());
                BmobApi.post(json, "https://api2.bmob.cn/1/requestPasswordReset", new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {
                        loginActivity.runOnUiThread(() -> Toast.makeText(loginActivity, "发送邮件失败，请检查", Toast.LENGTH_SHORT).show());
                    }
                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) {
                        loginActivity.runOnUiThread(() -> Toast.makeText(loginActivity, "已发送改密邮件", Toast.LENGTH_SHORT).show());
                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }).setNeutralButton("取消",null).show();
    }
    public void setBinding(LoginActivity loginActivity) {
        LoginVM.loginActivity=loginActivity;
    }
    public void onActivityResult(int requestCode, int resultCode) {
        if (requestCode==1&&resultCode==2){//是注册成功来的
            SharedPreferences.Editor edit = App.sp.edit();
            edit.putBoolean("autoLogin",true);//注册登录后都可以自动登录
            edit.apply();
            loginActivity.startActivity(new Intent(loginActivity, MainActivity.class));
            loginActivity.finish();
        }
    }
}